# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jhkim

from coin.base.book import BookBuilderBase
from coin.exchange.upbit_v1.kr_rest.product import UpbitProduct


class BookEntry(object):
  def __init__(self, price, qty):
    self.price = float(price)
    self.qty = float(qty)


class BookBuilder(BookBuilderBase):
  ProductType = UpbitProduct

  def __init__(self, native_symbol, book_builder_observer=None):
    super().__init__('Upbit', native_symbol, book_builder_observer=book_builder_observer)

  def snapshot(self, bids: list, asks: list):
    for data in bids:
      price, qty = [float(value) for value in data]
      self._insert_bid(price, qty, insert_only=True)
    for data in asks:
      price, qty = [float(value) for value in data]
      self._insert_ask(price, qty, insert_only=True)

  def _insert_bid(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._bid_price_map
    self._bid_price_map[price] = entry

  def _insert_ask(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._ask_price_map
    self._ask_price_map[price] = entry

  def _delete_bid(self, price):
    del self._bid_price_map[price]

  def _delete_ask(self, price):
    del self._ask_price_map[price]
